package com.fsgom.common.util;

import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

public class EncryptUtils {

	private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/ZeroBytePadding";
	private static final String KEY_STRING = "FSGomIsCuteBaby!";
	private static final String CIPHER_PROVIDER = "BC";
	private Cipher encrypter;
	private Cipher decrypter;
	
	public EncryptUtils() {
		if (Security.getProvider(CIPHER_PROVIDER) == null) {
			Security.addProvider(new BouncyCastleProvider());
		}
		byte[] key = KEY_STRING.getBytes();
		SecretKeySpec sks = new SecretKeySpec(key, KEY_ALGORITHM);
		try {
			encrypter = Cipher.getInstance(CIPHER_ALGORITHM, CIPHER_PROVIDER);
			encrypter.init(Cipher.ENCRYPT_MODE, sks);
			decrypter = Cipher.getInstance(CIPHER_ALGORITHM, CIPHER_PROVIDER);
			decrypter.init(Cipher.DECRYPT_MODE, sks);
		} catch (Exception e) {
			throw new AssertionError(e);
		}
	}
	
	/**
	  * String을 암호화하여 리턴한다
	  * @param data; 암호화할 문자열
	  * @return String
	  */
	public String encrypt(String data) throws Exception {
		if (data == null) {
			return null;
		}
	
		byte[] encryptedData = null;
		try {
			encryptedData = encrypter.doFinal(data.getBytes());
		} catch (IllegalBlockSizeException e) {
			System.err.println(e.getMessage());
		}
		return new String(Base64.encode(encryptedData));
	}
	
	/**
	  * String을 복호화하여 리턴한다.
	  * @param encrypredData; 복호화할 문자열
	  * @return String;
	  */
	public String decrypt(String encryptedData) {
		if (encryptedData == null) {
			return null;
		}
		byte[] decryptedData = Base64.decode(encryptedData);
		String decStr = null;
		try {
			decStr = new String(decrypter.doFinal(decryptedData));
		} catch (IllegalBlockSizeException e) {
			System.err.println(e.getMessage());
		} catch (BadPaddingException e) {
			System.err.println(e.getMessage());
		} 
		return decStr;
	}
	
	
	
}
